<template>
  <div class="container">
    <TaskChatDialog
      :model-value="drawerVisile"
      @close="handleClose"
      append-to-body
      width="30%"
      destroy-on-close
      :close-on-click-modal="false">
      <template #header>
        <span class="title">当前选择时间</span>
      </template>
      <el-form ref="formRef" :model="form" status-icon :rules="rules" label-width="auto">
        <el-form-item label="开始时间" prop="planBegintime">
          <el-date-picker
            style="width: 100%"
            v-model="form.planBegintime"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="" />
        </el-form-item>
        <el-form-item label="结束时间" prop="planEndtime">
          <el-date-picker
            style="width: 100%"
            v-model="form.planEndtime"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="disabledDateFun"
            placeholder="" />
        </el-form-item>
        <el-form-item label="共计(小时)" prop="planCostHour">
          <el-input v-model.number="form.planCostHour" />
          <!-- <el-input-number v-model="form.planCostHour" :min="1" :max="10" /> -->
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resetForm(formRef)">取消</el-button>
          <el-button type="primary" @click="submitForm(formRef)" :loading="loading">保存</el-button>
        </span>
      </template>
    </TaskChatDialog>
  </div>
</template>
<script setup>
import { updateTask } from '@/assets/api/task'
import dayjs from 'dayjs'
const props = defineProps(['drawerVisile', 'addTaskInfo'])
const emits = defineEmits(['closeDialog'])
import useEventBus from '@/use/use-event-bus.js'
const eventBus = useEventBus()
const dict = useDictionary(['work_time'])
import { useDictionary } from '@/use/use-dictionary'
import { ElMessage } from 'element-plus'

const formRef = ref(null)
const form = reactive({
  planBegintime: '',
  planEndtime: '',
  planCostHour: '',
})

const { planBegintime, planEndtime, planCostHour } = toRefs(form)

// 时间范围设置
const disabledDateFun = (time) => {
  if (time.getTime() <= new Date(planBegintime.value).getTime()) {
    return true
  } else {
    return false
  }
}

const checkHour = (rule, value, callback) => {
  const maxValue = (dayjs(form.planEndtime).diff(dayjs(form.planBegintime), 'day') + 1) * dict.getCode('work_time', '5')
  if (!value) {
    return callback(new Error('请输入共计用时'))
  } else if (typeof value !== 'number') {
    return callback(new Error('请输入数字'))
  }
  if (value > maxValue) {
    callback(new Error(`最大时间不可超过${maxValue}小时`))
  } else {
    callback()
  }
}

const rules = reactive({
  planCostHour: [{ validator: checkHour, trigger: 'blur' }],
  planBegintime: [{ required: true, message: '请选择开始时间', trigger: 'blur' }],
  planEndtime: [{ required: true, message: '请选择结束时间', trigger: 'blur' }],
})

/**
 * 关闭抽屉
 */
const handleClose = () => {
  emits('closeDialog')
}

watch(
  () => props.addTaskInfo,
  (newValue) => {
    planBegintime.value = dayjs(newValue.startStr).format('YYYY-MM-DD')
    planEndtime.value = dayjs(newValue.endStr).format('YYYY-MM-DD')
    planCostHour.value = newValue.planCostHour || getDateDiff(planBegintime.value, planEndtime.value)
  }
)

// watch([planBegintime, planEndtime], ([newStartTime, newEndTime], [oldStartTime, oldEndTime]) => {
//   if (newStartTime && newEndTime) {
//     planCostHour.value = getDateDiff(planBegintime.value, planEndtime.value)
//   }
// })

const loading = ref(false)
function submitForm() {
  formRef.value.validate(async (valid) => {
    if (valid) {
      if (props.addTaskInfo.taskId) {
        loading.value = true
        let data = { ...props.addTaskInfo, ...form }
        const res = await updateTask(data)
        if (res.code === 200) {
          eventBus.emit('updateSelectDate', data, 'edit')
          emits('closeDialog')
        } else {
          ElMessage.error(res.msg)
        }
        loading.value = false
      } else {
        eventBus.emit('updateSelectDate', form)
        emits('closeDialog')
      }
    }
  })
}
const resetForm = (formEl) => {
  // if (!formEl) return
  emits('closeDialog')
  formEl.resetFields()
}

//获取两个日期相差的天数
function getDateDiff(startTime, endTime) {
  let str = ''
  const start = dayjs(startTime)
  const end = dayjs(endTime)
  str = end.diff(start, 'day')
  console.log(str)

  return (str + 1) * 8
}
</script>
<style scoped></style>
